<template>
    <div class="login-container">
        <div class="login-box">
            <h2 class="login-title">欢迎登录</h2>
            <div class="form-item">
                <input type="text" v-model="username" placeholder="用户名" />
            </div>
            <div class="form-item">
                <input type="password" v-model="password" placeholder="密码" />
            </div>
            <div class="form-item captcha-container">
                <input type="text" v-model="captchaCode" placeholder="验证码" class="captcha-input" maxlength="10" />
                <div class="captcha-image" @click="refreshCaptcha">
                    <img v-if="captchaUrl" :src="captchaUrl" alt="验证码" title="点击刷新验证码" />
                    <div v-else class="captcha-loading">加载中...</div>
                </div>
            </div>
            <div class="form-item">
                <button @click="handleLogin" class="login-btn" :disabled="loading">
                    {{ loading ? '登录中...' : '登录' }}
                </button>
            </div>
            <div class="form-options">
                <div class="remember-me">
                    <input type="checkbox" id="remember" v-model="rememberMe" />
                    <label for="remember">记住我</label>
                </div>
                <div class="forgot-password">
                    <a href="#">忘记密码?</a>
                </div>
            </div>
            <div class="register-link">
                <span>还没有账号?</span>
                <router-link to="/register">立即注册</router-link>
            </div>
            <div v-if="errorMsg" class="error-message">
                {{ errorMsg }}
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { userService } from '@/http/userService'
import { captchaService } from '@/http/captchaService'

const router = useRouter()
const username = ref('')
const password = ref('')
const captchaCode = ref('')
const captchaGuid = ref('')
const captchaUrl = ref('')
const rememberMe = ref(false)
const loading = ref(false)
const errorMsg = ref('')

// 初始化验证码
onMounted(() => {
    refreshCaptcha()
})

// 刷新验证码
const refreshCaptcha = async () => {
    try {
        captchaUrl.value = '' // 清空验证码图片，显示加载状态
        // 如果已有GUID则使用现有GUID，否则生成新的
        const captcha = await captchaService.refreshCaptcha(captchaGuid.value || undefined)
        captchaGuid.value = captcha.guid
        // 添加时间戳防止缓存
        captchaUrl.value = `${captcha.imageUrl}&t=${Date.now()}`
        captchaCode.value = '' // 清空验证码输入
        console.log('验证码GUID:', captchaGuid.value) // 调试用，可以删除
    } catch (error) {
        console.error('刷新验证码失败:', error)
        errorMsg.value = '获取验证码失败，请刷新页面重试'
    }
}

const handleLogin = async () => {
    // 清空错误消息
    errorMsg.value = ''

    // 验证表单输入
    if (!username.value || !password.value) {
        errorMsg.value = '请输入用户名和密码'
        return
    }

    if (!captchaCode.value) {
        errorMsg.value = '请输入验证码'
        return
    }

    if (!captchaGuid.value) {
        errorMsg.value = '验证码无效，请刷新验证码'
        await refreshCaptcha()
        return
    }

    // 验证用户名和密码长度
    if (username.value.length < 3 || username.value.length > 50) {
        errorMsg.value = '用户名长度应为3-50个字符'
        return
    }

    if (password.value.length < 6 || password.value.length > 50) {
        errorMsg.value = '密码长度应为6-50个字符'
        return
    }

    loading.value = true

    console.log('登录请求参数:', {
        username: username.value,
        password: '******',

    }) // 调试用，可以删除

    try {
        // 直接将验证码信息传递给登录方法
        const response = await userService.login({
            username: username.value,
            password: password.value,
            rememberMe: rememberMe.value
        })
        if (response.success) {
            router.push('/menu')
        } else {
            errorMsg.value = response.message || '登录失败，请检查用户名、密码或验证码'
            await refreshCaptcha() // 刷新验证码
        }
    } catch (error) {
        console.error('登录失败:', error)
        errorMsg.value = '登录失败，请稍后再试'
        await refreshCaptcha() // 刷新验证码
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.login-container {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #9e9e9e;
    position: relative;
}

.login-box {
    width: 400px;
    background-color: #fff;
    border-radius: 8px;
    padding: 30px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.login-title {
    text-align: center;
    margin-bottom: 30px;
    font-size: 24px;
    color: #333;
    font-weight: normal;
}

.form-item {
    margin-bottom: 20px;
}

.form-item input[type="text"],
.form-item input[type="password"] {
    width: 100%;
    padding: 12px 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.captcha-container {
    display: flex;
    align-items: center;
    gap: 10px;
}

.captcha-input {
    flex: 1;
}

.captcha-image {
    width: 120px;
    height: 40px;
    cursor: pointer;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f9f9f9;
}

.captcha-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.captcha-loading {
    font-size: 12px;
    color: #666;
}

.login-btn {
    width: 100%;
    padding: 12px;
    background-color: #4a90e2;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
}

.login-btn:hover:not(:disabled) {
    background-color: #3a7bc8;
}

.login-btn:disabled {
    background-color: #a0c0e8;
    cursor: not-allowed;
}

.form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
    font-size: 14px;
}

.remember-me {
    display: flex;
    align-items: center;
    color: #666;
}

.remember-me input {
    margin-right: 5px;
}

.forgot-password a {
    color: #4a90e2;
    text-decoration: none;
}

.error-message {
    color: #e74c3c;
    text-align: center;
    margin-top: 15px;
    font-size: 14px;
}

.register-link {
    text-align: center;
    margin-top: 20px;
    font-size: 14px;
    color: #666;
}

.register-link a {
    color: #4a90e2;
    margin-left: 5px;
    text-decoration: none;
}

.register-link a:hover {
    text-decoration: underline;
}

@media (max-width: 500px) {
    .login-box {
        width: 90%;
        max-width: 400px;
    }

    .captcha-container {
        flex-direction: column;
        align-items: stretch;
    }

    .captcha-image {
        margin-top: 10px;
        width: 100%;
    }
}
</style>